import styled from 'styled-components'
import useSwitch from '../../hook/switch'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { serverTime } from '../../service'
import { formatSecondCountDown } from '../../utils/time'


const Container = styled.div`
    display: flex;
    justify-content: center;
    padding: .5rem 0;
    box-sizing: border-box;
`

const Time = styled.span`
    font-size: 10px;
    color: ${(prop) => prop.theme.text.normal};
    line-height: 9px;
`

interface Props {
    className?: string
}

const Trade: React.FC<Props> = ({ className }) => {
    const [config] = useSwitch()
    const tradeTime = useMemo(() => config.numberForKey('tradeTime', 0), [config])

    const [leftTime, setLeftTime] = useState(0)
    const [timeStr, setTimeStr] = useState('')

    const time = useCallback(async () => {
        const res = await serverTime()
        return res
    }, [])

    useEffect(() => {
        if (tradeTime <= 0) {
            return
        }

        const format = async () => {
            const res = await time()
            if (!res.success || !res.data) {
                setLeftTime(0)
                return
            }
            setLeftTime(tradeTime - res.data)
        }
        format()
    }, [tradeTime, time])

    useEffect(() => {
        let temp = Math.floor(leftTime / 1000)
        const format = 'DDd:HHh:mmm:sss'
        setTimeStr(formatSecondCountDown(temp, { format }))
        if (temp <= 0) {
            return
        }

        const interval = 1000
        const secondInterval = interval / 1000
        const timer = setInterval(() => {
            temp = temp - secondInterval
            setTimeStr(formatSecondCountDown(temp, { format }))
            if (temp <= 0) {
                clearInterval(timer)
            }
        }, interval)

        return () => {
            clearInterval(timer)
        }
    }, [leftTime])

    return <>
        {leftTime > 0 && <Container
            className={className}
        >
            <Time>{timeStr}</Time>
        </Container>}
    </>
}

export default Trade